#pragma once

#include "log.hpp"
#include "err.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>

class Sock
{
public:
    static int Socket()
    {
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if (sock < 0)
        {
            logMessage(FATAL, "创建套接字失败");
            exit(SOCK_ERR);
        }
        logMessage(NORMAL, "创建套接字成功：%d", sock);

        int opt = 1;
        setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); // 允许处于TIME_WAIT状态的端口被重新绑定
        return sock;
    }

    static void Bind(int listenSock, uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local)); // 新的，最好先全置为0
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        int n = bind(listenSock, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            logMessage(FATAL, "绑定失败");
            exit(BIND_ERR);
        }
        logMessage(NORMAL, "绑定成功");
    }

    static void Listen(int listenSock)
    {
        int n = listen(listenSock, 5);
        if (n < 0)
        {
            logMessage(FATAL, "监听启动失败");
            exit(LISTEN_ERR);
        }
        logMessage(NORMAL, "监听启动成功");
    }

    static int Accept(int listenSock, std::string *ip, uint16_t *port)
    {
        struct sockaddr_in sockaddr;
        socklen_t len;
        int sock = accept(listenSock, (struct sockaddr *)&sockaddr, &len);
        if (sock < 0)
        {
            logMessage(FATAL, "连接失败");
            exit(ACCEPT_ERR);
        }
        *ip = inet_ntoa(sockaddr.sin_addr);
        *port = ntohs(sockaddr.sin_port);
        logMessage(NORMAL, "连接成功, [%s:%d]", (*ip).c_str(), *port);
        return sock;
    }
};